package com.sunday.pinxinghui.model.lifecircle;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sunday.common.adapter.CommenAdapter;
import com.sunday.common.adapter.ViewHolder;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.utils.SpannalbeStringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.CircleImageView;
import com.sunday.common.widgets.NoScrollGridView;
import com.sunday.common.widgets.banner.ConvenientBanner;
import com.sunday.common.widgets.banner.holder.ViewHolderCreator;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.adapter.IndexAdHolder;
import com.sunday.pinxinghui.adapter.StringHolder;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.entity.BannerImg;
import com.sunday.pinxinghui.entity.Comment;
import com.sunday.pinxinghui.entity.ProductDetail;
import com.sunday.pinxinghui.model.WebViewActivity;
import com.sunday.pinxinghui.model.mine.CouponListActivity;
import com.sunday.pinxinghui.model.mine.CouponListFragment;
import com.sunday.pinxinghui.model.order.CartActivity;
import com.sunday.pinxinghui.model.products.CommentListActivity;
import com.sunday.pinxinghui.model.products.ShowVideoActivity;
import com.sunday.pinxinghui.network.ApiClient;
import com.sunday.pinxinghui.widgets.MyRatingBar;
import com.sunday.pinxinghui.widgets.ProductWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sunday.pinxinghui.network.ApiClient.CUSTOMER_URL;

/**
 * Created by 刘涛 on 2017/8/29.
 */

public class CouponDetailActivity extends BaseActivity {


    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.banner)
    ConvenientBanner banner;
    @Bind(R.id.coupon_title)
    TextView couponTitle;
    @Bind(R.id.coupon_desc)
    TextView couponDesc;
    @Bind(R.id.coupon_addr)
    TextView couponAddr;
    @Bind(R.id.comment_num)
    TextView commentNum;
    @Bind(R.id.comment_user_logo)
    CircleImageView commentUserLogo;
    @Bind(R.id.comment_user_name)
    TextView commentUserName;
    @Bind(R.id.rating_bar)
    MyRatingBar ratingBar;
    @Bind(R.id.comment_user_time)
    TextView commentUserTime;
    @Bind(R.id.comment_user_content)
    TextView commentUserContent;
    @Bind(R.id.comment_user_imgs)
    NoScrollGridView commentUserImgs;
    @Bind(R.id.comment_layout)
    RelativeLayout commentLayout;
    @Bind(R.id.btn_more_comment)
    TextView btnMoreComment;
    @Bind(R.id.web_view)
    WebView webView;
    @Bind(R.id.coupon_score)
    TextView couponScore;
    @Bind(R.id.coupon_time)
    TextView couponTime;
    @Bind(R.id.btn_change)
    TextView btnChange;

    private int couponId;
    private ProductDetail productDetail;
    private long memberId;
    private String endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coupon_detail);
        ButterKnife.bind(this);
        titleView.setText("电子券详情");
        couponId = getIntent().getIntExtra("couponId", 0);
        endDate = getIntent().getStringExtra("endDate");
        memberId = BaseApplication.getInstance().getMember().getId();
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        getDetail();

    }

    private void getDetail() {
        Call<ResultDO<ProductDetail>> call = ApiClient.getApiAdapter().couponDetail(couponId, memberId);
        call.enqueue(new Callback<ResultDO<ProductDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<ProductDetail>> call, Response<ResultDO<ProductDetail>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    productDetail = response.body().getResult();
                    updateView();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<ProductDetail>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });

    }

    private void updateView() {
        if (productDetail == null) {
            return;
        }
        List<BannerImg> bannerImgs = new ArrayList<>();
        if (productDetail.getImages() != null && productDetail.getImages().size() > 0) {
            bannerImgs.addAll(productDetail.getImages());
        }
        banner.getLayoutParams().width = DeviceUtils.getDisplay(mContext).widthPixels;
        banner.getLayoutParams().height = DeviceUtils.getDisplay(mContext).widthPixels * 118 / 100;
        banner.startTurning(3000);
        final IndexAdHolder indexAdHolder = new IndexAdHolder();
        banner.setPages(new ViewHolderCreator<IndexAdHolder>() {
            @Override
            public IndexAdHolder createHolder() {
                return indexAdHolder;
            }
        }, bannerImgs)
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        banner.notifyDataSetChanged();

        indexAdHolder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BannerImg item = (BannerImg) v.getTag();
                if (item.getType() == 2) {
                    intent = new Intent(mContext, ShowVideoActivity.class);
                    intent.putExtra("url", item.getUrl());
                    startActivity(intent);
                }
            }
        });


        couponTitle.setText(productDetail.getProductName());
        couponDesc.setText(productDetail.getSummary());
        couponAddr.setText(productDetail.getAddress());

        commentNum.setText(SpannalbeStringUtils.setTextColor("用户评价", ContextCompat.getColor(mContext, R.color._333)));
        commentNum.append(SpannalbeStringUtils.setTextColor(String.format("(%d)", productDetail.getCommentCount()),
                ContextCompat.getColor(mContext, R.color._999)));
        if (productDetail.getCommentCount() != null && productDetail.getCommentCount() == 0) {
            btnMoreComment.setText("暂无评价");
            commentLayout.setVisibility(View.GONE);
        } else {
            commentLayout.setVisibility(View.VISIBLE);
            if (productDetail.getComments() != null && productDetail.getComments().size() > 0) {
                Comment comment = productDetail.getComments().get(0);
                Glide.with(mContext)
                        .load(comment.getMemberLogo())
                        .error(R.mipmap.ic_default)
                        .into(commentUserLogo);
                commentUserName.setText(comment.getMemberName());
                commentUserTime.setText(comment.getTime());
                commentUserContent.setText(comment.getContent());
                ratingBar.setRating((int) comment.getScore(), R.drawable.rating_bar, false, 15);
                if (comment.getImages() != null && comment.getImages().size() > 0) {
                    commentUserImgs.setAdapter(new CommenAdapter<String>(mContext, comment.getImages(), R.layout.list_comment_img_item) {
                        @Override
                        public void convert(ViewHolder helper, String item, int position) {
                            ImageView imgView = helper.getView(R.id.comment_img);
                            Glide.with(mContext)
                                    .load(item)
                                    .error(R.mipmap.ic_default)
                                    .into(imgView);
                        }
                    });
                }
            }
        }


        WebSettings webSettings = webView.getSettings();
        //webSettings.setJavaScriptEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl(productDetail.getDetailUrl());

        couponScore.setText(productDetail.getScore() + "积分");
        couponTime.setText("有效期至" + endDate);

    }

    @OnClick({R.id.btn_more_comment, R.id.btn_change})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_more_comment:
                if (productDetail.getComments() != null) {
                    intent = new Intent(mContext, CouponCommentListActivity.class);
                    intent.putExtra("couponId", couponId);
                    startActivity(intent);
                }
                break;
            case R.id.btn_change:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("温馨提示");
                builder.setMessage("确认兑换吗");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exchangeCoupon(couponId);
                        dialog.dismiss();
                    }
                });
                builder.show();
                break;
        }
    }

    private void exchangeCoupon(int couponId) {
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().couponExchange(couponId, BaseApplication.getInstance().getMember().getId());
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("温馨提示");
                    builder.setMessage("兑换成功,是否立即使用？");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("去使用", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            intent = new Intent(mContext, CouponListActivity.class);
                            intent.putExtra("page", 1);
                            startActivity(intent);
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }


}
